package com.weipai.springboot.module.service.impl;

import com.weipai.springboot.enums.DemandStatus;
import com.weipai.springboot.enums.OrderStatus;
import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.enums.UserType;
import com.weipai.springboot.model.*;
import com.weipai.springboot.model.api.PageResult;
import com.weipai.springboot.model.api.Response;
import com.weipai.springboot.module.dao.*;
import com.weipai.springboot.module.dao.AdminDao;
import com.weipai.springboot.module.dao.CashRecordDao;
import com.weipai.springboot.module.dao.CustomerDao;
import com.weipai.springboot.module.mapper.AdminMapper;
import com.weipai.springboot.module.mapper.CustomerMapper;

import com.weipai.springboot.module.service.CustomerService;
import com.weipai.springboot.module.util.DateUtils;
import com.weipai.springboot.module.util.SessionUserUtil;
import com.weipai.springboot.module.util.wxPayUtil.HttpRequest;
import com.weipai.springboot.util.PasswordHelper;
import com.weipai.springboot.util.WxPayMessage;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Author: 曹朋飞
 * @Date: 2018/08/09 11:26
 * <p>
 * 客户
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    private static final Logger log = LoggerFactory.getLogger(CustomerServiceImpl.class);
    @Autowired
    private CenterDao centerDao;
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private CashRecordDao cashRecordDao;
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private SessionUserUtil sessionUserUtil;
    @Autowired
    private SystemDao systemDao;
    @Autowired
    private DemandDao demandDao;
    @Autowired
    private ArtisanDao artisanDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ReputationHistoryDao reputationHistoryDao;


    //用户注册
    @Override
    public Response save(String mobile, String newCode, String oldCode, String password, String inviCode, String code) {
        Response response = new Response();
        Customer customer = new Customer();
        if (null == newCode || null == oldCode) {
            response.setCode(RetCode.SMS_CODE_PUT);
            return response;
        }
        if (!newCode.equals(oldCode)) {
            response.setCode(RetCode.SMS_CODE_VERIFY_FAIL);
            return response;
        }
        if (null == mobile || null == password) {
            response.setCode(RetCode.COLD_ALL);
            return response;
        }
        if (customerDao.getCustomerByMobile(mobile) > 0) {
            response.setCode(RetCode.COLD_phone);
            return response;
        }
        if (adminDao.verifyCustomerByInviCode(inviCode) == 0) {
            response.setCode(RetCode.INVICODE_VALID);
            return response;
        } else {
            customer.setAdminCode(inviCode);
        }
        if (code != null && !"".equals(code)) {
            WxPayMessage wxPayMessage = new WxPayMessage();
            //页面获取openId接口
            String getopenid_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
            String param = "appid=" + wxPayMessage.getAppId() + "&secret=" + wxPayMessage.getSecret() + "&code=" + code + "&grant_type=authorization_code";
            //向微信服务器发送get请求获取openIdStr
            String openIdStr = HttpRequest.sendGet(getopenid_url, param);
            JSONObject json = JSONObject.fromObject(openIdStr);//转成Json格式
            String openId = json.getString("openid");//获取openId
            customer.setWxOppenid(openId);
        }
        customer.setCustomerMobile(mobile);
        customer.setCustomerNickname(mobile);
        customer.setCustomerPassword(PasswordHelper.encryptPassword(password, mobile));
        customer.setCustomerLoginName(mobile);
        customer.setMemberLevelId("1");     //默认 等级为  一级会员
        customer.setCustomerCategoryId(1);  //默认 身份为  普通会员
        customer.setCustomerReputation(0);  //默认 信用值  为0
        customer.setUseReputation(0);     // 默认 已用信用值 为0

        if (1 == customerDao.insert(customer)) {
            response.setCode(RetCode.SUCCESS);
        } else {
            log.debug("添加用户失败:{}", customer.getCustomerNickname());
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }


    //重置密码
    @Override
    public Response resetPasswords(String mobile, String newCode, String oldCode, String customerPassword, String password2) {
        Response response = new Response();
        //判断验证码是否正确
        if (!newCode.equals(oldCode)) {
            response.setCode(RetCode.COLD);
        } else {
            //判断二次密码是否正确
            if (!customerPassword.equals(password2)) {
                response.setCode(RetCode.PWD_ERROR);
            } else {
                if (0 != customerDao.updateByPrimaryKey22(mobile, PasswordHelper.encryptPassword(customerPassword, mobile))) {
                    response.setCode(RetCode.SUCCESS);
                } else {
                    response.setCode(RetCode.REQUEST_ERROR);
                }
            }
        }
        return response;
    }

    //重置手机号
    @Override
    public Response resetPhone(String customerLoginName, String password, String customerId, String newCode, String oldCode) {
        Response response = new Response();
        //判断验证码是否一致
        if (!newCode.equals(oldCode)) {
            response.setCode(RetCode.COLD);
        } else {
            //判断密码是否正确
            Customer customer = customerDao.getCustomerById(customerId);
            String passwordOld = customer.getCustomerPassword(); //原手机号  原密码
            String password22 = PasswordHelper.encryptPassword(password, customer.getCustomerMobile()); //密码加盐
            if (!passwordOld.equals(password22)) {
                response.setCode(RetCode.PWD_ERROR);
            } else {
                String passwordNew = PasswordHelper.encryptPassword(password, customerLoginName);  //形成新密码保存
                if (1 == customerDao.resetPhone(customerLoginName, customerId, passwordNew)) {      //重置手机号 密码
                    response.setCode(RetCode.SUCCESS);
                } else {
                    response.setCode(RetCode.REQUEST_ERROR);
                }
            }
        }
        return response;
    }


    //更改会员的等级
    @Override
    public Response changeCustomerMemberLevel(String customerId, String memberLevelId, String remark) {
        Response response = new Response();
        if (customerDao.changeCustomerMemberLevel(customerId, memberLevelId, remark) == 1) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //更改会员的类别
    @Override
    public Response changeCustomerCategory(String customerId, String categoryId) {
        Response response = new Response();
        if (customerDao.changeCustomerCategory(customerId, categoryId) == 1) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }


    //分页查询
    @Override
    public List<Customer> selectAllByDel(int del, String search, String sort, String way) {
        return customerDao.selectAllByDel(del, search, sort, way);
    }

    //查询用户详情
    @Override
    public Response getCustomerById(String id) {
        Response response = new Response();
        Customer customer = customerDao.getCustomerById(id);
        if (null != customer) {
            response.setCode(RetCode.SUCCESS);
            response.put("customer", customer);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //修改用户资料
    @Override
    public Response update(Customer customer) {
        Response response = new Response();
        customer.setUpdateTime(DateUtils.timeFormat(System.currentTimeMillis()));
        if (1 == customerDao.updateByPrimaryKey(customer)) {
            response.setCode(RetCode.SUCCESS);
        } else {
            log.debug("修改员工信息失败:{}", customer.getCustomerNickname());
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //删除
    @Override
    public Response deleteById(String id) {
        Response response = new Response();
        Customer customer = customerDao.getCustomerById(id);

        if (UserType.CUSTOMER.getType() == customer.getCustomerCategoryId()) {
            if (customer.getUseReputation() < customer.getCustomerReputation()) {
                response.setCode(RetCode.RETURN_REPUTATION);
                return response;
            }
        }

        if (customerDao.updateDel(id) == 1) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }

        return response;
    }

    //批量删除
    @Override
    public Response batchDeleteById(String[] id) {
        Response response = new Response();
        for (int i = 0; i < id.length; i++) {
            Customer customer = customerDao.getCustomerById(id[i]);
            if (UserType.CUSTOMER.getType() == customer.getCustomerCategoryId()) {
                if (customer.getUseReputation() < customer.getCustomerReputation()) {
                    response.setCode(RetCode.RETURN_REPUTATION);
                    return response;
                }
            }
        }

        if (customerDao.batchDeleteById(id) > 0) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //更改用户的昵称
    @Override
    public Response changeNickname(String customerId, String nickname) {
        Response response = new Response();
        if (customerDao.verifyCustomerByNickname(nickname) > 0) {
            response.put("code", 401);
            response.put("msg", "昵称已有人使用，请从新输入");
            return response;
        }
        if (customerDao.updateNicknameById(customerId, nickname) == 1) {
            response.setCode(RetCode.SUCCESS);
        } else {
            log.debug("更改用户昵称失败:{}", customerId);
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //我的收益
    //根据用户类型判断返回  员工收益列表  或  技工收益列表
    @Override
    public Response getMyIncomes() {
        Response response = new Response();
        Customer customer = sessionUserUtil.getUserAttr();
        List<Map<String, Object>> list = new ArrayList<>();
        if (UserType.ARTISAN.getType() == customer.getCustomerCategoryId()) {
//            //技工 查询需求
//            Map<String, Object> commissionRate = systemDao.getCommissionRateByType(1);
//            double rate = (100 - Integer.valueOf(commissionRate.getOrDefault("commissionRate", 0) + "")) / 100.00;
            Artisan artisan = artisanDao.getArtisanByCustomerId(customer.getCustomerId());
//            List<Demand> demandList = demandDao.demandListByArtisanId(artisan.getArtisanId(), DemandStatus.COMPLETED.getStatus());
//            if (demandList != null) {
//                for (Demand demand : demandList) {
//                    Map<String, Object> mp = new HashMap<>();
//                    mp.put("demandId", demand.getDemandId());
//                    mp.put("address", demand.getProvince() + demand.getCity() + demand.getCounty());
//                    mp.put("createTime", demand.getCreateTime());
//                    mp.put("demandName", demand.getDemandName());
//                    mp.put("demandMoney", demand.getDemandMoney() * rate);
//                    list.add(mp);
//                }
//            }
            list=artisanDao.getMyIncomesList(artisan.getArtisanId());
            if (artisan != null) {
                response.put("artisanHeadImg", artisan.getArtisanHeadImg());
            }
        } else {
            //员工 查询订单收益
            list = customerDao.getMyIncomes(customer.getCustomerId());
        }
        response.put("list", list);
        response.put("cashMoney", customer.getHcashMoney());   //可提现金额 单位分
        //增加已提现金额
        int cashedAmount = cashRecordDao.getCashAmount(customer.getCustomerId());
        response.put("cashedAmount", cashedAmount); //已提现金额
        response.put("total", customer.getCashMoney()); //总收益
        response.setCode(RetCode.SUCCESS);
        return response;
    }


    //我的团队
    @Override
    public Response getMyTeams() {
        Response response = new Response();
        String customerId = sessionUserUtil.getUserAttr().getCustomerId();
        //查询 员工的推荐码
        Admin admin = adminDao.getAdminByCustomerId(customerId);
        if (admin != null) {
            String adminCode = admin.getAdminCode();
            List<Customer> list = customerDao.getMyTeams(adminCode);
            response.put("list", list);
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }

        return response;
    }

    //后台分页查询用户
    @Override
    public Response list(Integer page, Integer size, String draw, String search, String type, String statement) {
        Integer start = (page - 1) * size;
        List<Map<String, Object>> customer = customerDao.list(start, size, type, search);
        Integer totalNum = customerDao.listByPageAmount(type, search);
        PageResult<Map<String, Object>> pageList = new PageResult<>(customer, page, size, totalNum, draw);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        if (!customer.isEmpty()) {
            if ("H".equals(statement)) {
                int size01 = customer.size();
                for (int i = 0; i < size01; i++) {
                    Map<String, Object> map = customer.get(i);
                    Map<String, Object> orderMap = orderDao.getOrderAmountByCustomerId(map.get("customerId").toString(), OrderStatus.SUCCESS.getStatus());
                    Map<String, Object> saleReturnMap = orderDao.getSaleReturnAmountByCustomerId(map.get("customerId").toString());
                    map.put("orderMap", orderMap);
                    map.put("saleReturnMap", saleReturnMap);
                }
            }
        }
        return response;
    }


    //更改用户的信誉值
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response changeCustomerReputation(String customerId, Integer useReputation) {
        Response response = new Response();
        Customer customer = customerDao.getCustomerById(customerId);
        if (useReputation > customer.getUseReputation()) {
            if (useReputation <= customer.getCustomerReputation()) {
                if (customer.getCustomerCategoryId() == 2) {
                    Customer customer1 = new Customer();
                    customer1.setCustomerId(customerId);
                    customer1.setUseReputation(useReputation);
                    customerDao.updateByPrimaryKey(customer1);
                    //保存信誉值记录
                    ReputationHistory reputation1 = new ReputationHistory();
                    reputation1.setCustomerId(customerId);
                    reputation1.setAmount(useReputation - customer.getUseReputation());
                    reputation1.setType(1);
                    reputationHistoryDao.insert(reputation1);
                    response.setCode(RetCode.SUCCESS);
                } else {
                    response.setCode(RetCode.CUSTOMER_CATEGORY_ERROR);
                }
            } else {
                response.setCode(RetCode.REPUTATION_FLOOR);
            }
        } else {
            response.setCode(RetCode.REPUTATION_ERROR);
        }

        return response;
    }


    //更改用户的状态
    @Override
    public Response changeStatus(String id, Integer status) {
        Response response = new Response();
        if (customerDao.changeStatus(id, status) == 1) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }


    //查询某一员工的推荐客户
    @Override
    public Response listByAdminCode(Integer page, Integer size, String draw, String adminCode, String search) {
        Integer start = (page - 1) * size;
        List<Map<String, Object>> customer = customerDao.listByAdminCode(start, size, adminCode, search);
        Integer totalNum = customerDao.listByAdminCodeAmount(adminCode, search);
        PageResult<Map<String, Object>> pageList = new PageResult<>(customer, page, size, totalNum, draw);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }

    //授信-信誉值
    @Override
    public Response saveCustomerReputation(String customerId, Integer reputation) {
        Response response = new Response();
        Customer customer = customerDao.getCustomerById(customerId);
        if (customer.getCustomerCategoryId() == 2) {
            int useReputation = customer.getUseReputation();
            int customerReputation = customer.getCustomerReputation();
            if (useReputation == customerReputation) {
                Customer customer1 = new Customer();
                customer1.setCustomerId(customerId);
                customer1.setCustomerReputation(reputation);
                customer1.setUseReputation(reputation);
                customerDao.updateByPrimaryKey(customer1);
                response.setCode(RetCode.SUCCESS);
            } else {
                response.setCode(RetCode.REPUTATION);
            }
        } else {
            response.setCode(RetCode.CUSTOMER_CATEGORY_ERROR);
        }
        return response;
    }

    //获取用户余额 信用卡信息
    @Override
    public Response getBalance(String customerId) {
        Response response = new Response();
        Customer customer = customerDao.getCustomerById(customerId);
        List<CustomerBank> banks = centerDao.getBankByCustomerId(customerId);
        if(banks.size()>0){
            String cashMoney=String.valueOf(customer.getCashMoney());
            String hcashMoney=String.valueOf(customer.getHcashMoney());
            response.setCode(RetCode.SUCCESS);
            response.put("data",banks);
            response.put("hcashMoney",hcashMoney);
            response.put("cashMoney",cashMoney);
        }else{
            response.setCode(RetCode.NO_BANKINFO);
        }
        return response;
    }
}
